﻿@("/***************************************************")
@("* 模块名称：" + Model.TableName + "Service")
@("* 功能概述：")
@("* 创建人：何贵祥")
@("* 创建时间：" + DateTime.Now.ToString("d") + "")
@("* 修改人：")
@("* 修改时间：")
@("* 修改描述：")
@("*************************************************/")
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using @(Model.Namespace).IService;
using @(Model.Namespace).IRepository;
using @(Model.Namespace).Model;
using @(Model.Namespace).Common.ExpressionExtensions;
@using System.Collections.Generic;
@using MICZ.CodeBuilder.ViewModels;

namespace @(Model.Namespace).Service
{ 
    @{
    List<BuilderColumnViewModel> _Columns = Model.Columns; bool IsDel = _Columns.Where(a => a.ColumnName.ToLower() == "isdel").Count() > 0 ? true : false;
    BuilderColumnViewModel IsDelColumn = _Columns.Where(a => a.ColumnName.ToLower() == "isdel").FirstOrDefault();
    var _Primarykey = _Columns.Where(asd => asd.ColumnIsPrimarykey == true).FirstOrDefault(); string PrimaryName = _Primarykey == null ? _Columns.FirstOrDefault().ColumnName : _Primarykey.ColumnName;
    }
    public class @(Model.TableName)Service : I@(Model.TableName)Service
    {   
        ISqlSugarRepository SqlSugarRepository;
        public @(Model.TableName)Service(ISqlSugarRepository _SqlSugarRepository)
        {
            SqlSugarRepository = _SqlSugarRepository;
        }

        #region 系统自动生成
        #region 获取
        @("/// <summary>")
        @("/// 获取一条数据")
        @("/// </summary>")
        @("/// <param name=\"expression\">树形表达式</param>")
        @("/// <param name=\"select\">查询列</param>")
        @("/// <param name=\"IsAll\">是否全局搜索(包含已删除)</param>")
        @("/// <returns></returns>")
        public async Task< @(Model.TableName)> Get(Expression< Func < @(Model.TableName), bool>> expression, string select = "*", bool IsAll = false)
        {
            return await Task.Run(() =>
            {
                @if(IsDel){
                    if (IsDelColumn.Type.ToLower() == "bool") { 
                    @("if(!IsAll)")@:
                        @("expression=expression.And(a => a." + IsDelColumn.ColumnName + " != true);")@:
                }
                    else {
                    @("if(!IsAll)")@:
                        @("expression=expression.And(a => a." + IsDelColumn.ColumnName + " != 1);")@:
                }
                }
                @(Model.TableName) model = SqlSugarRepository.Db.Queryable< @(Model.TableName) > ().Select(select).Take(1).Where(expression).ToList()?.FirstOrDefault();
                //@(Model.TableName) model = SqlSugarRepository.@(Model.TableName)Db.GetTop(expression);
                return model;
            });
        }

        @("/// <summary>")
        @("/// 获取多条数据")
        @("/// </summary>")
        @("/// <param name=\"page\">页面(page=0,rows=0则显示全部)</param>")
        @("/// <param name=\"rows\">页面条数(page=0,rows=0则显示全部)</param>")
        @("/// <param name=\"OrderBy\">排序</param>")
        @("/// <param name=\"expression\">树形表达式</param>")
        @("/// <param name=\"select\">查询列</param>")
        @("/// <param name=\"IsAll\">是否全局搜索(包含已删除)</param>")
        @("/// <returns></returns>")
        public async Task< List< @(Model.TableName)>> GetList(int page, int rows, string OrderBy, Expression< Func < @(Model.TableName), bool>> expression, string select = "*", bool IsAll=false)
        {
            return await Task.Run(() =>
            {
                @if(IsDel){
                    if (IsDelColumn.Type.ToLower() == "bool") { 
                    @("if(!IsAll)")@:
                        @("expression=expression.And(a => a." + IsDelColumn.ColumnName + " != true);")@:
                }
                    else {
                    @("if(!IsAll)")@:
                        @("expression=expression.And(a => a." + IsDelColumn.ColumnName + " != 1);")@:
                }
                }
                List < @(Model.TableName) > model = new List< @(Model.TableName) > ();
                if (string.IsNullOrWhiteSpace(OrderBy))
                    OrderBy += "CreateTime desc";
                if (page == 0 && rows == 0)
                {
                    model = SqlSugarRepository.Db.Queryable< @(Model.TableName) > ().Select(select).OrderBy(OrderBy).Where(expression).ToList();
                    //model = SqlSugarRepository.@(Model.TableName)Db.GetLists(OrderBy, expression, select);
                }
                else
                {
                    model = SqlSugarRepository.Db.Queryable< @(Model.TableName) > ().Select(select).OrderBy(OrderBy).Where(expression).ToPageList(page, rows);
                    //model = SqlSugarRepository.@(Model.TableName)Db.GetList(page, rows, OrderBy, expression, select);
                }
                return model;
            });
        }

        @("/// <summary>")
        @("/// 获取数据总数")
        @("/// </summary>")
        @("/// <param name=\"expression\">树形表达式</param>")
        @("/// <param name=\"IsAll\">是否全局搜索(包含已删除)</param>")
        @("/// <returns></returns>")
        public async Task<long> GetListTotal(Expression<Func< @(Model.TableName), bool>> expression,bool IsAll=false)
        {
            return await Task.Run(() =>
            {
                @if(IsDel){
                    if (IsDelColumn.Type.ToLower() == "bool") { 
                    @("if(!IsAll)")@:
                        @("expression=expression.And(a => a." + IsDelColumn.ColumnName + " != true);")@:
                }
                    else {
                    @("if(!IsAll)")@:
                        @("expression=expression.And(a => a." + IsDelColumn.ColumnName + " != 1);")@:
                }
                }
                var datatable = SqlSugarRepository.Db.Queryable< @(Model.TableName) > ().Select("COUNT(1)").Where(expression).ToDataTable();
                long cmd = Convert.ToInt64(datatable.Rows[0][0]);
                //long cmd = SqlSugarRepository.@(Model.TableName)Db.GetListTotal(expression);
                return cmd;
            });
        }
        #endregion

        #region 提交插入
        @("/// <summary>")
        @("/// 创建数据")
        @("/// </summary>")
        @("/// <param name=\"model\">实体</param>")
        @("/// <param name=\"obj\">过滤对象a=>new {a.ID}</param>")
        @("/// <returns></returns>")
        public async Task<long> Create(@(Model.TableName) model, Expression< Func < @(Model.TableName), object>> obj = null)
        {
            return await Task.Run(() =>
            {
                @if(IsDel){
                    if (IsDelColumn.Type.ToLower() == "bool")
                    @("model." + IsDelColumn.ColumnName + " = false;")
                    else
                    @("model." + IsDelColumn.ColumnName + " = 0;")
                }
                long cmd = 0;
                if (obj == null)
                 cmd = SqlSugarRepository.Db.Insertable(model).IgnoreColumns(ignoreNullColumn: true).ExecuteCommand();
                else
                 cmd = SqlSugarRepository.Db.Insertable(model).IgnoreColumns(obj).IgnoreColumns(ignoreNullColumn: true).ExecuteCommand();
                //cmd = SqlSugarRepository.@(Model.TableName)Db.InserEntity(model, obj);
                return cmd;
            });
        }

        @("/// <summary>")
        @("/// 创建数据")
        @("/// </summary>")
        @("/// <param name=\"model\">List<T>实体</param>")
        @("/// <param name=\"obj\">过滤对象a=>new {a.ID}</param>")
        @("/// <returns></returns>")
        public async Task<long> Create(List< @(Model.TableName) > model, Expression< Func < @(Model.TableName), object>> obj = null)
        {
            return await Task.Run(() =>
            {
                @if(IsDel){
                    if (IsDelColumn.Type.ToLower() == "bool") {
                        @("foreach (var item in model)")
                        @("{")
                        @("item." + IsDelColumn.ColumnName + " = false;")
                        @("}")
                    }
                    else
                    {
                        @("foreach (var item in model)")
                        @("{")
                        @("item." + IsDelColumn.ColumnName + " = 0;")
                        @("}")
                    }
                }
                long cmd = 0;
                if (obj == null)
                 cmd = SqlSugarRepository.Db.Insertable(model).ExecuteCommand();
                else
                 cmd = SqlSugarRepository.Db.Insertable(model).IgnoreColumns(obj).ExecuteCommand();
                //cmd = SqlSugarRepository.@(Model.TableName)Db.InserEntity(model, obj);
                return cmd;
            });
        }
        #endregion

        #region 更新
        @("/// <summary>")
        @("/// 更新数据")
        @("/// </summary>")
        @("/// <param name=\"model\">实体</param>")
        @("/// <returns></returns>")
        public async Task<int> Update(@(Model.TableName) model)
        {
            return await Task.Run(() =>
            {
                int cmd = SqlSugarRepository.Db.Updateable(model).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
                //int cmd = SqlSugarRepository.@(Model.TableName)Db.UpdateEntity(model);
                return cmd;
            });
        }

        @("/// <summary>")
        @("/// 更新数据")
        @("/// </summary>")
        @("/// <param name=\"model\">实体</param>")
        @("/// <returns></returns>")
        public async Task<int> Update(@(Model.TableName) model, Expression< Func < @(Model.TableName), bool>> expression)
        {
            return await Task.Run(() =>
            {
                int cmd = SqlSugarRepository.Db.Updateable(model).Where(expression).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
                //int cmd = SqlSugarRepository.@(Model.TableName)Db.UpdateEntity(model, expression);
                return cmd;
            });
        }  

        @("/// <summary>")
        @("/// 更新数据")
        @("/// </summary>")
        @("/// <param name=\"model\">实体</param>")
        @("/// <returns></returns>")
        public async Task<int> Update(@(Model.TableName) model, string[] cols, Expression< Func < @(Model.TableName), bool>> expression)
        {
            return await Task.Run(() =>
            {
                int cmd = SqlSugarRepository.Db.Updateable(model).IgnoreColumns(cols).Where(expression).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
                //int cmd = SqlSugarRepository.@(Model.TableName)Db.UpdateEntity(model, cols, expression);
                return cmd; 
            });
        } 
        
        @("/// <summary>")
        @("/// 更新数据")
        @("/// </summary>")
        @("/// <param name=\"model\">实体</param>")
        @("/// <returns></returns>")
        public async Task<int> Update(@(Model.TableName) model, Expression< Func < @(Model.TableName), object>> obj, Expression< Func < @(Model.TableName), bool>> expression)
        {
            return await Task.Run(() =>
            {
                int cmd = SqlSugarRepository.Db.Updateable(model).IgnoreColumns(obj).Where(expression).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
                //int cmd = SqlSugarRepository.@(Model.TableName)Db.UpdateEntity(model, obj, expression);
                return cmd;
            });
        }
        #endregion

        #region 删除
        @if(IsDel)
        {
            @("/// <summary>")@:
            @("/// 逻辑删除")@:
            @("/// </summary>")@:
            @("/// <param name=\"expression\">树形表达式</param>")@:
            @("/// <returns></returns>")@:
            @:public async Task<int> SoftRemove(Expression< Func < @(Model.TableName), bool>> expression)
            @:{
                @:return await Task.Run(() =>
                @:{
                @:List<@(Model.TableName)> getlist = SqlSugarRepository.Db.Queryable< @(Model.TableName) > ().Where(expression).ToList();
                //@:List<@(Model.TableName)> getlist = SqlSugarRepository.@(Model.TableName)Db.GetLists("", expression);
                @:if (getlist == null)
                    @:return 0;
                @{
                    @:foreach (var item in getlist)
                    @:{
                    if (IsDelColumn.Type.ToLower() == "bool")
                    @("item." + IsDelColumn.ColumnName + " = true;")
                    else
                    @("item." + IsDelColumn.ColumnName + " = 1;")
                    @:}
                }
                @:
                @:int cmd = SqlSugarRepository.Db.Updateable(getlist).IgnoreColumns(a => new {@("a." + PrimaryName) }).Where(expression).ExecuteCommand();
                //@:int cmd = SqlSugarRepository.@(Model.TableName)Db.UpdateEntity(getlist, a => new {@("a." + PrimaryName) }, expression);
                @:return cmd;
                @:});
            @:}

            @("/// <summary>")@:
            @("/// 恢复逻辑删除")@:
            @("///</summary>")@:
            @("/// <param name=\"expression\">树形表达式</param>")@:
            @("/// <returns></returns>")@:
            @:public async Task<int> CancelSoftRemove(Expression< Func < @(Model.TableName), bool>> expression)
            @:{
                @:return await Task.Run(() =>
                @:{
                @:List<@(Model.TableName)> getlist = SqlSugarRepository.Db.Queryable < @(Model.TableName) > ().Where(expression).ToList();
                //@:List<@(Model.TableName)> getlist = SqlSugarRepository.@(Model.TableName)Db.GetLists("", expression);
                @:if (getlist == null)
                    @:return 0;
                @{
                    @:foreach (var item in getlist)
                    @:{
                    if (IsDelColumn.Type.ToLower() == "bool")
                    @("item." + IsDelColumn.ColumnName + " = false;")
                    else
                    @("item." + IsDelColumn.ColumnName + " = 0;")
                    @:}
        }
                @:
                @:int cmd = SqlSugarRepository.Db.Updateable(getlist).IgnoreColumns(a => new {@("a." + PrimaryName) }).Where(expression).ExecuteCommand();
                //@:int cmd = SqlSugarRepository.@(Model.TableName)Db.UpdateEntity(getlist, a => new {@("a."+PrimaryName) }, expression);
                @:return cmd;
                @:});
            @:}
        }

        @("/// <summary>")
        @("/// 实体删除")
        @("/// </summary>")
        @("/// <param name=\"model\">实体</param>")
        @("/// <returns></returns>")
        public async Task<int> Remove(Expression< Func < @(Model.TableName), bool>> expression)
        {
            return await Task.Run(() =>
            {
                int cmd = SqlSugarRepository.Db.Deleteable< @(Model.TableName) > ().Where(expression).ExecuteCommand(); ;
                //int cmd = SqlSugarRepository.@(Model.TableName)Db.DeleteEntity(expression);
                return cmd;
            });
        }
        #endregion
        #endregion
    }


}
